package com.knight.thread;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * 
 * Copy Right Information :  <br>
 * Project : java study <br>
 * Description : 任务拆分合并<br>
 * Author :  Knight<br>
 * Version : 1.0.0 <br>
 
 * Date : 2018-11-10<br>
 */
public class ForkJoinPoolTest {
	
	class ForkJoinTask extends RecursiveTask<Integer>{
		
		private int[] array;

		private static final long serialVersionUID = 1L;
		
		public ForkJoinTask(int []array) {
			this.array = array;
		}

		@Override
		protected Integer compute() {
			if(array == null && array.length == 0) {
				return 0;
			}
			int length = array.length;
			List<ForkJoinTask> list = new ArrayList<ForkJoinTask>();
			if(length > 1000) {
				ForkJoinTask task1 = new ForkJoinTask(Arrays.copyOfRange(array, 0, length/2-1));
				ForkJoinTask task2 = new ForkJoinTask(Arrays.copyOfRange(array, length/2, length-1));
				list.add(task1);
				list.add(task2);
			}else {
				Arrays.sort(array);
				return array[length-1];
			}
			
			Iterator<ForkJoinTask> it = list.iterator();
			while(it.hasNext()) {
				it.next().fork();
			}
			
			List<Integer> maxList = new ArrayList<Integer>();
			for(ForkJoinTask task : list) {
				Integer inte = task.join();
				maxList.add(inte);
//				System.out.println(inte);
			}
			
			return Collections.max(maxList);
		}
		
	}

	public static void main(String[] args) {
		int[] arrays = new int[10000000];
		for(int i=0; i<10000000; i++) {
			int idx = new Random().nextInt(10000);
			arrays[i] = idx;
		}
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				long startTime = System.currentTimeMillis();
				Arrays.parallelSort(arrays);
				System.out.println("最大值为" + arrays[arrays.length-1] + "-----耗时：" + (System.currentTimeMillis()-startTime));
			}
		}).start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				long startTime = System.currentTimeMillis();
				Arrays.sort(arrays);
				System.out.println("最大值为" + arrays[arrays.length-1] + "-----耗时：" + (System.currentTimeMillis()-startTime));
			}
		}).start();
		
		
		ForkJoinPool pool = new ForkJoinPool(5);
		ForkJoinPoolTest test = new ForkJoinPoolTest();
		ForkJoinTask task = test.new ForkJoinTask(arrays);
		
		long startTime = System.currentTimeMillis();
		Integer maxNum = pool.invoke(task);
		System.out.println("最大值为" + maxNum + "-----耗时：" + (System.currentTimeMillis()-startTime));

	}

}
